/**
 * Copyright (C) 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package psn.shan.xml.enhancedvalidator.rules.comparator;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.inject.Named;

import org.springframework.context.annotation.Scope;

/**
 * IntegerComparator <br />
 *
 * Class or Interface Description 
 * 
 * @author Shan
 * 
 */
@Named("DateComparator")
@Scope("prototype")
public class DateComparator extends AbstractComparator<Date> {
	
	private final static String mPattern = "yyyy-MM-dd";

	@Override
	public void setOperandOne(String aOperandOne) throws Exception {
		DateFormat lFormat = new SimpleDateFormat(mPattern);
		mOperandOne = lFormat.parse(aOperandOne);
	}

	@Override
	public void setOperandTwo(String aOperandTwo) throws Exception {
		DateFormat lFormat = new SimpleDateFormat(mPattern);
		mOperandTwo = lFormat.parse(aOperandTwo);
	}
	
	/*
	 * http://en.wikipedia.org/wiki/Julian_day
	 */
	private int getJulianDay(Date aDate) {
		Calendar lCalendar = Calendar.getInstance();
		lCalendar.setTime(aDate);
		int lYear = lCalendar.get(Calendar.YEAR);
		int lMonth = lCalendar.get(Calendar.MONTH) + 1;
		int lDay = lCalendar.get(Calendar.DAY_OF_MONTH);
		
		int a = (14 - lMonth) / 12;
		int y = lYear + 4800 - a;
		int m = lMonth + 12 * a - 3;
		int lJulianDay = lDay + (153 * m + 2)/5 + 365*y + y/4 - y/100 + y/400 - 32045;
		return lJulianDay;		
	}

	@Override
	protected int computeDifference() {
		return getJulianDay(mOperandOne)- getJulianDay(mOperandTwo);
	}
}
